const app = getApp()
var util = require('../../utils/date.js')
var webhost = app.globalData.webhost;
var getAccess;

Page({
  data: {
    imgList: [],
    Type: ''
  },

  del(e) {
    var index = +e.currentTarget.dataset.id;
    var list = this.data.imgList;
    list.splice(index, 1);
    this.setData({
      imgList: list
    })
  },

  upLoadImg(tempFilePaths, i){
    var that = this;
    var fileName = that.data.dir + '/' + app.globalData.driverAccount + util.Format("yyyyMMddhhmmssS", new Date());
    // var url = that.data.host;
    var url = 'https://snap.fjxylc.com';
    var imgList = that.data.imgList;
    var item = {
      picturePath: url + '/' + fileName
    }
    wx.uploadFile({
      url: url,
      filePath: tempFilePaths[i],
      name: 'file',
      formData: {
        name: tempFilePaths[i],
        key: fileName,
        policy: that.data.policy,
        OSSAccessKeyId: that.data.accessid,
        success_action_status: "200",
        signature: that.data.signature
      },
      success(res) {
        imgList.push(item);        
        that.setData({
          imgList: imgList
        })
        i++;
        if(i < tempFilePaths.length){
          that.upLoadImg(tempFilePaths, i);
        }
      },
      fail() {
        wx.showToast({
          title: '第' + i + '张图片上传失败',
          icon: 'none'
        })
      }
    })
  },

  picClick() {
    var that = this;
    if (!that.data.accessid) {
      wx.showToast({
        title: '未获取上传权限',
        icon: 'none'
      })
      return false;
    }
    var count = 9;
    count = 9 - that.data.imgList.length;
    if (count <= 0) {
      wx.showToast({
        title: '最多上传9张图片',
        icon: 'none'
      })
      return false;
    }
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        if (tempFilePaths) {
          var i = 0;
          that.upLoadImg(tempFilePaths, i);
        }
      }
    })
  },

  upload(){
    var that = this;
    console.log(app.globalData.plan);
    console.log(app.globalData.task);
    if( that.data.imgList.length == 0 ){
      wx.showToast({
        title: '请先上传图片',
        icon: 'none'
      })
      return false
    }
    
    var taskid = '';
    var taskCode = app.globalData.plan.taskCode;
    var actionCode;
    if (app.globalData.plan.snap){
      actionCode = app.globalData.plan.snap.actionCode;
    } else{
      actionCode = '';
    }
    if(that.data.Type == 'task'){
      taskid = app.globalData.task.taskid;
      taskCode = app.globalData.task.taskCode;
      actionCode = app.globalData.task.snap.actionCode;
    }
    var data = [{
      String: {
        driverAccount: app.globalData.driverAccount,
        sessionid: app.globalData.sessionid,
        planId: app.globalData.planid,
        taskid: taskid,
        taskCode: taskCode,
        actionCode: actionCode,
        dataList: that.data.imgList
      }
    }]
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'doPlanEventContainImage', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(data)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      complete() {
        wx.hideNavigationBarLoading();
      },
      success({
        data
      }) {
        if (data.code && data.code == '000000') {
          wx.showToast({
            title: '上传成功！'
          })
          that.setData({imgList: []});
          setTimeout(function(){
            var pages = getCurrentPages();
            var currPage = pages[pages.length - 1];   //当前页面
            var prevPage = pages[pages.length - 2];  //上一个页面
            // console.log(prevPage.route);
            wx.navigateBack({
              url: prevPage.route
            })
          }, 1200);
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '获取上传权限失败，请下拉刷新页面！',
          icon: 'none'
        })
      }
    })
  },

  onLoad: function(options) {
    var that = this;

    if(options.lt == 'plan'){
      that.setData({ Type: 'plan' });
    } else if (options.lt == 'task'){
      that.setData({ Type: 'task' });
    }

    getAccess = function() {
      var data = [{
        String: {
          sessionid: app.globalData.sessionid
        }
      }]
      wx.request({
        url: webhost,
        data: {
          eap_username: "driver",
          eap_password: "Driver2018",
          boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
          methodName: 'getFileUploadPermission', //调用的具体方法
          returnType: "json", //返回参数类型
          parameters: JSON.stringify(data)
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        complete() {
          wx.hideNavigationBarLoading();
        },
        success({
          data
        }) {
          if (data.code && data.code == '000000') {
            that.setData({
              accessid: data.data.accessid,
              policy: data.data.policy,
              signature: data.data.signature,
              dir: data.data.dir,
              host: data.data.host
            })
          }
        },
        fail: function(res) {
          wx.showToast({
            title: '获取上传权限失败，请下拉刷新页面！',
            icon: 'none'
          })
        }
      })
    }

    getAccess();
  },


  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    getAccess();
    setTimeout(function(){
      wx.stopPullDownRefresh();
    }, 1500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})